package pers.vic.dubbo.common.tool;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pers.vic.boot.util.CommonUtils;

import javax.servlet.http.HttpSession;

/**
 * 描述:
 * @author Vic.xu
 * @date 2022-01-24 10:13
 */
public class DubboTools {

    public static final String TRACE_ID = "dubbo-trance-id";

    /**
     * 保存在当前线程中的tranceId
     */
    public static final ThreadLocal<String> DUBBO_TRANCE_LOCAL = new ThreadLocal<>();

    /**
     * 把trance id 存入当前线程
     * @param tranceId
     */
    public static void setLocalTranceId(String tranceId){
        DUBBO_TRANCE_LOCAL.set(tranceId);
    }

    public static void removeLocalTranceId(){
        DUBBO_TRANCE_LOCAL.remove();
    }

    /**
     * 获取当前线程中的trance id
     * @return
     */
    public static String getLocalTranceId(){
        return DUBBO_TRANCE_LOCAL.get();
    }


    public static String generateTranceId(){
        //获取sessionId
        String sessionId = currentsessionId();
        if (sessionId != null) {
            return sessionId;
        }
        System.out.println("DubboTools#generateTranceId session is null ");
        return CommonUtils.randomUuid();
    }

    public static String currentsessionId(){
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attr == null) {
            return null;
        }
        HttpSession session = attr.getRequest().getSession(false);
        if (session == null) {
            return null;
        }
        return session.getId();
    }
}
